import { Request, Response } from 'express';
import { InterestTag, User } from '../models';
import { Op } from 'sequelize';
import { AppError } from '../utils/errorHandler';

// 获取所有兴趣标签
export const getInterestTags = async (req: Request, res: Response): Promise<void> => {
    try {
        const tags = await InterestTag.findAll({
            order: [['name', 'ASC']]
        });
        res.json(tags);
        return;
    } catch (error) {
        console.error('获取兴趣标签失败:', error);
        res.status(500).json({ message: '获取兴趣标签失败' });
    }
};

// 搜索兴趣标签
export const searchTags = async (req: Request, res: Response): Promise<void> => {
    try {
        const { keyword } = req.query;
        if (!keyword) {
            throw new AppError('请输入搜索关键词', 400);
        }

        const tags = await InterestTag.findAll({
            where: {
                name: {
                    [Op.like]: `%${keyword}%`
                }
            },
            order: [['name', 'ASC']]
        });

        res.json(tags);
        return;
    } catch (error) {
        console.error('搜索兴趣标签失败:', error);
        res.status(500).json({ message: '搜索兴趣标签失败' });
    }
};

// 创建兴趣标签
export const createInterestTag = async (req: Request, res: Response): Promise<void> => {
    try {
        const { name, category, description, icon } = req.body;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        // 检查标签名是否已存在
        const existingTag = await InterestTag.findOne({ where: { name } });
        if (existingTag) {
            throw new AppError('标签名已存在', 400);
        }

        const tag = await InterestTag.create({
            name,
            category,
            description,
            icon
        });

        res.status(201).json(tag);
    } catch (error) {
        console.error('创建兴趣标签失败:', error);
        res.status(500).json({ message: '创建兴趣标签失败' });
    }
};

// 更新用户标签
export const updateUserTags = async (req: Request, res: Response): Promise<void> => {
    try {
        const { tagIds } = req.body;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const user = await User.findByPk(userId);
        if (!user) {
            throw new AppError('用户不存在', 404);
        }

        await user.setTags(tagIds);
        res.json({ message: '标签更新成功' });
    } catch (error) {
        console.error('更新用户标签失败:', error);
        res.status(500).json({ message: '更新用户标签失败' });
    }
};

// 获取用户标签
export const getUserTags = async (req: Request, res: Response): Promise<void> => {
    try {
        const { userId } = req.params;
        const user = await User.findByPk(userId, {
            include: [{
                model: InterestTag,
                as: 'tags',
                attributes: ['id', 'name', 'category', 'description', 'icon']
            }]
        });

        if (!user) {
            throw new AppError('用户不存在', 404);
        }

        res.json(user.tags);
    } catch (error) {
        console.error('获取用户标签失败:', error);
        res.status(500).json({ message: '获取用户标签失败' });
    }
}; 